#include "XmlClient.hh"

XmlClient::XmlClient(QString const& host, uint16_t port):
    host(host),
    port(port),
    socket()
{
    connect(&socket, SIGNAL(readyRead()), this, SLOT(read_data()));
    socket.connectToHost(host, port);
    socket.waitForConnected(-1);
}

XmlClient::~XmlClient() {
    socket.disconnectFromHost();

    if (socket.state() != QAbstractSocket::UnconnectedState)
        socket.waitForDisconnected(-1);
}

void XmlClient::send(QString const& message) {
    QByteArray data = message.toUtf8();

    uint64_t size = data.length();
    socket.write(
      QByteArray(reinterpret_cast< char* >(&size), sizeof(uint64_t)) + data
    );
    socket.waitForBytesWritten(-1);
}

void XmlClient::read_data() {
    while (
      static_cast<uint64_t>(socket.bytesAvailable()) >= sizeof(uint64_t)
    ) {
        QByteArray inputBuffer = socket.read(sizeof(uint64_t));
        uint64_t size = *reinterpret_cast< uint64_t* >(inputBuffer.data());

        while (static_cast<uint64_t>(socket.bytesAvailable()) < size)
            socket.waitForReadyRead(-1);

        inputBuffer = socket.read(size);
        emit data_available(QString(inputBuffer));
    }
}
